use slint::Image;
use tiff::decoder::{DecodingResult,Decoder,Limits};
use image::{error::{DecodingError, UnsupportedError}, DynamicImage, ImageBuffer, ImageResult, Luma, Rgb};
use std::fs::File;


pub struct ImageLoader{
   pub path :String
}
impl ImageLoader{
    pub fn load(&self)->ImageResult<DynamicImage>{
        let img_file = File::open(&self.path).expect("cannot find image");
        let mut decoder = Decoder::new(img_file).expect("cannot create decoder");
        let dim = decoder.dimensions().expect("cannot get dim");
        
        let mut custom_limits=Limits::default();
        custom_limits.decoding_buffer_size=30*1024*1024*1024;
        custom_limits.intermediate_buffer_size = 8*1024*1024*1024;
        custom_limits.ifd_value_size = 2*1024*1024*1024;
        decoder = decoder.with_limits(custom_limits);
        println!("colortype:{:?}",decoder.colortype());
        println!("dimensions:{:?}",dim);
        let tiffimage = match decoder.read_image(){
            Ok(result)=>result,
            Err(err)=>{
                return Err(image::ImageError::Decoding(
                    DecodingError::from_format_hint(image::error::ImageFormatHint::Exact(image::ImageFormat::Tiff))
                ));
            }
        };
        

        let image = match tiffimage{
    
            tiff::decoder::DecodingResult::U16(imgdata)=>{
                let mut img_buffer = ImageBuffer::new(dim.0, dim.1);
                println!("process 16");
                for y in 0..dim.1{
                    for x in 0..dim.0{
                        let idx:usize = (y*dim.0+x).try_into().unwrap();
                        img_buffer.put_pixel(x, y, Luma([imgdata[idx]]));
                    }
                }
                img_buffer
            },
            _=>{return Err(image::ImageError::Unsupported(
                UnsupportedError::from_format_and_kind(
                    image::error::ImageFormatHint::Exact(image::ImageFormat::Tiff),
                    image::error::UnsupportedErrorKind::Format(image::error::ImageFormatHint::Exact(image::ImageFormat::Tiff))
                    )
                )
            );}
        };
        Ok(DynamicImage::ImageLuma16(image))
    }
}
